<?php

namespace App\Controllers;

use Framework\Database;
use Framework\Validation;
use Framework\Session;
use Framework\Middleware\Authorisation;
use Framework\Middleware\Authorise;

class ListingController
{
    protected $db;

    public function __construct()
    {
        $config = require basePath('config/db.php');
        $this->db = new Database($config);
    }

    /**
     * 展示所有岗位
     * 
     * @return void
     */
    public function index()
    {
        $listings = $this->db->query('SELECT * FROM listing ORDER BY created_at DESC')->fetchAll();

        loadView('listings/index',[
            'listings'=>$listings
        ]);
    }

    /**
     * 展示创建职位表单
     * 
     * @return void
     */
    public function create()
    {
        loadView('listings/create');
    }

    /**
     * 展示单一岗位页面
     * 
     * @return void
     */
    public function show($params)
    {
        $id = $params['id'] ?? '';

        $params = [
            'id' => $id
        ];

        $listing = $this->db->query('SELECT * FROM listing WHERE id = :id',$params)->fetch();

        if(!$listing){
            ErrorController::notFound('该岗位不存在！');
            return;
        }


        loadView('listings/show',[
            'listing'=>$listing
        ]);
    }

    /**
     * 
    * @return void
    */

    public function store()
    {
        $allowedFields=['title','description','salary','tags','company','address','city','province','phone','email','requirements','benefits'];

        $newListingData = array_intersect_key($_POST,array_flip($allowedFields));

        $newListingData['user_id'] = Session::get('user')['id'];

        $newListingData = array_map('sanitize',$newListingData);

        $requiredFields = ['title','description','email','city','province'];

        $errors = [];
        foreach ($requiredFields as $field){
            if(empty($newListingData[$field]) || !Validation::string($newListingData[$field])){
                $errors[$field] = ucfirst($field) . '为必需项';
            }
        }

        if(!empty($errors)){
            loadView('listings/create',[
                'errors' => $errors,
                'listing' => $newListingData
            ]);
        }else{
            $fields =[];

            foreach ($newListingData as $field => $value){
                $fields[] = $field; 
            }
            $fields = implode(', ',$fields);
            $values = [];

            foreach($newListingData as $field => $value){
                if($value === ''){
                    $newListingData[$field] = null;
                }
                $values[] = ':' . $field;
            }

            $values = implode(', ',$values);
            $query = "INSERT INTO listing({$fields}) VALUES ({$values})";
            $this->db->query($query,$newListingData);
            Session::setFlashMessage('success_message','已成功创建职位!');
            redirect('/listings');
        }
    }


    /**
     * 
     * @param array
     * @return void
     */
    public function destroy($params)
    {
        $id = $params['id'];
        $params = [
            'id' => $id
        ];
        $listing = $this->db->query('SELECT * FROM listing WHERE id =:id',$params)->fetch();
        if(!$listing){
            ErrorController::notFound('职位不存在！');
            return;
        }

        if(!Authorisation::isOwner($listing->user_id)){
            inspect($_SESSION);
            Session::setFlashMessage('error_message','你没有权限删除此职位!');
            return redirect('/listings/' . $listing->id);
        }
        $this->db->query('DELETE FROM listing WHERE id = :id',$params);
        Session::setFlashMessage('error_message','你没有权限删除此职位！');
        redirect('/listings');
    }
    /**
     * 
     * @param array
     * @return void
     */
    public function edit($params)
    {
        $id=$params['id'] ?? '';
        $sparms = [
            'id' =>$id
        ];
        $listing = $this->db->query('SELECT * FROM listing WHERE id = :id',$params)->fetch();

        if(!$listing){
            ErrorController::notFound('职位不存在!');
            return;
        }

        if(!Authorisation::isOwner($listing->user_id)){
            Session:setFlashMessage('error_message','你没有权限修改此职位!');
            return redirect('/listings/' . $listing->id);
        }
        loadView('listings/edit',[
            'listing'=>$listing
        ]);
    }


   /**
     * 更新列表项数据
     * 
     * @param array $params
     * @return void
     * 
     */
    public function update($params)
    {
        // 从参数中尝试获取列表项ID，如果没有提供，则默认为空字符串
        $id = $params['id'] ?? '';

        // 准备用于数据库查询的参数
        $params = [
            'id' => $id
        ];

        // 查询数据库以确认列表项是否存在
        $listing = $this->db->query('SELECT * FROM listing WHERE id = :id', $params)->fetch();

        // 如果列表项不存在
        if (!$listing) {
            // 调用错误控制器并结束方法执行
            ErrorController::notFound('职位不存在! ');
            return;
        }

        if(!Authorisation::isOwner($listing->user_id)){
            Session::setFlashMessage('error_message','你没有权限修改此职位!');
            return redirect('/listings/' . $listing->id);
        }

        // 定义可以从表单接受的字段列表
        $allowedFields = ['title', 'description', 'salary', 'tags', 'company', 'address', 'city','province','phone',
        'email','requirements','benefits'];

        // 过滤并保留允许的字段
        $updateValues = array_intersect_key($_POST, array_flip($allowedFields));

        // 对过滤后的数据进行清洗
        $updateValues = array_map('sanitize', $updateValues);

        // 定义必须填写的字段列表
        $requiredFields = ['title','description','salary','email','city','province'];
        
        // 初始化错误收集数组
        $errors = [];

        // 检查必填字段是否已填写且符合要求
        foreach ($requiredFields as $field) {
            if (empty($updateValues[$field]) || !Validation::string($updateValues[$field])) {
                $errors[$field] = ucfirst($field) . '为必须项!';
            }
        }

        // 如果存在错误
        if (!empty($errors)) {
            // 重新加载编辑视图并传递错误信息与当前列表数据
            loadView('listings/edit', [
                'listing' => $listing,
                'errors' => $errors
            ]);
            exit;
        }else{
            // 构建 SQL 更新语句中的字段赋值部分
            $updateFields = [];
            foreach (array_keys($updateValues) as $field) {
                $updateFields[] = "{$field} = :{$field}";
            }

            // 将字段赋值部分合成字符串
            $updateFields = implode(', ', $updateFields);

            // 构建完整的 SQL 更新语句
            $updateQuery = "UPDATE listing SET $updateFields WHERE id = :id";

            // 在更新数据中包括 ID
            $updateValues['id'] = $id;

            // 执行 SQL 更新操作
            $this->db->query($updateQuery, $updateValues);

            // 设置成功信息
            Session::setFlashMessage('success_message','职位信息已更新！');

            // 重定向到列表项详情页面
            redirect('/listings/' . $id);
        }
    }

    public function search()
    {
        $keywords = isset($_GET['keywords']) ? trim($_GET['keywords']) : '';
        $location = isset($_GET['location']) ? trim($_GET['location']) : '';

        $query = "SELECT * FROM listing WHERE
                (title LIKE :keywords OR description LIKE :keywords OR
                tags LIKE :keywords OR company LIKE :keywords) AND
                (city LIKE :location OR province LIKE :location)";
        
        $params = [
            'keywords'=>"%{$keywords}%",
            'location'=>"%{$location}%"
        ];

        $listings = $this->db->query($query,$params)->fetchAll();

        loadView('/listings/index',[
            'listings'=>$listings,
            'keywords'=>$keywords,
            'location'=>$location
        ]);
    }

}